<template>
	<view class="page">
		
		<view class="search">
			<u-search placeholder="搜索你想要去的电站"
				v-model="formData.searchName" 
				:showAction="false" 
				height="35" 
				@search="onSearch"
			></u-search>
		</view>
		
		<view class="list" v-if="list && list.length > 0">
			<charger-item :list="list" :distance="true" @gotodetail="gotodetail"></charger-item>
		</view>
		
		<!-- 空状态 -->
		<view class="empty" v-else><u-empty mode="data"></u-empty></view>
		
		<!-- 加载更多 -->
		<u-loadmore v-if="list && list.length > 0" :status="loadMoreStatus" />
		
		<u-back-top :scroll-top="scrollTop"></u-back-top>
	</view>
</template>

<script>
	import { mapState, mapActions } from 'vuex'
	export default {
		data() {
			return {
				list: [],
				formData: {
					pageNo: 1,
					pageSize: 15,
					searchName: '',
					// 新增：添加位置信息字段
					userLatitude: null,
					userLongitude: null
				},
				isLoading: false,
				isFinished: false,
				scrollTop: 0
			}
		},
		computed: {
			...mapState(['mylocation', 'mylocationState']),
			loadMoreStatus() {
				if (this.isLoading) return 'loading'
				if (this.isFinished) return 'nomore'
				return 'loadmore'
			}
		},
		onLoad() {
			// 在页面加载时，检查并获取位置信息
			if (this.mylocationState && this.mylocation) {
				this.formData.userLatitude = this.mylocation.latitude;
				this.formData.userLongitude = this.mylocation.longitude;
				this.getList();
			} else {
				// 如果没有位置信息，可以给一个提示
				console.log('未获取到位置信息，无法计算距离。');
				// 这里也可以调用一个获取位置的方法，但为了简洁，我们假设首页已处理
				this.getList(); // 仍然调用getList，但位置信息为null
			}
		},
		onReachBottom() {
			this.getList();
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			onSearch() {
				if (!this.formData.searchName) {
					return uni.$u.toast('请输入关键词')
				}
				this.isLoading = false;
				this.isFinished = false;
				this.formData.pageNo = 1;
				this.getList();
			},
			
			getList() {
				if (this.isFinished || this.isLoading) return
				this.isLoading = true
				
				// 将位置信息加入到请求参数中
				const formData = { 
					pageNo: this.formData.pageNo, 
					pageSize: this.formData.pageSize,
					userLatitude: this.formData.userLatitude,
					userLongitude: this.formData.userLongitude
				};
				if (this.formData.searchName) {
					formData.searchName = this.formData.searchName
				}
				
				// 调用与首页相同的API或确保后端能处理位置参数的API
				// 假设后端接口 testChargingList 也能处理位置参数
				this.$http_api.testChargingList(formData).then(res => {
					if (!res) {
						this.isFinished = true
						return
					}
					let { records = [], total = 0, current = 1, pages = 1 } = res || {}
					records = this.processStationLabels(records); // 处理标签
					this.list = this.formData.pageNo === 1 ? records : [...this.list, ...records]
					this.isFinished = current >= pages
					this.formData.pageNo++
				}).catch(err => {
					this.isFinished = true
				}).finally(() => {
					this.isLoading = false
				})
			},
			// 处理充电站标签
			processStationLabels(records) {
				if (!Array.isArray(records)) {
					return []
				}
				
				return records.map(item => {
					try {
						let labels = [];
						// 配套服务
						if (item.serviceTypes && Array.isArray(item.serviceTypes)) {
							labels.push(...this.getFilterLabels('serviceType', item.serviceTypes))
						}
						// 科技特色
						if (item.technologyFeatures && Array.isArray(item.technologyFeatures)) {
							labels.push(...this.getFilterLabels('technologyFeatures', item.technologyFeatures))
						}
						// 停车场、停车费、充电方式标签为单个
						labels = this.getFilterOtherLabels(item.parkingArea, item.parkingFee, item.chargingType, labels)
						item.labels = labels
						return item;
					} catch (error) {
						item.labels = []
						return item
					}
				})  
			},
			getFilterLabels(type, indices) {
				if (!Array.isArray(indices) || !this.$store.state[type]) {
					return [];
				}
				const labels = indices.map(index => {
					const item = this.$store.state[type].find(label => label.value == index)
					return item.name.replaceAll('\r\n', '')
				})
				return labels
			},
			// 单选筛选条件
			getFilterOtherLabels(parkingArea, parkingFee, chargingType, labels) {
				// 停车场
				const parkingAreaLabel = this.$store.state.parkingType.find((item, index) => parkingArea == item.value)
				if (parkingAreaLabel) {
					labels.push(parkingAreaLabel.name)
				}
				// 停车费
				const parkingFeeLabel = this.$store.state.parkingFee.find((item, index) => parkingFee == item.value)
				if (parkingFeeLabel) {
					labels.push(parkingFeeLabel.name)
				}
				// 充电方式
				const chargingTypeLabel = this.$store.state.chargingType.find((item, index) => chargingType == item.value)
				if (chargingTypeLabel) {
					labels.push(chargingTypeLabel.name)
				}
				return labels;
			},
			//跳转详情
			gotodetail(id) {
				uni.navigateTo({
					url:"/pages/index/detail?id="+id + "&source=test" 
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	.page {
		padding-bottom: calc(40rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
	}
	
	.search {
		margin: 20rpx;
	}
</style>
